<template>
  <div class="page_all" style="color: #333333 !important;">
    <div class="img_box">
      <img src="../../../static/images/1234.png" alt="">
    </div>
    <p class="title_info">通过 EMS 脉冲技术，深入皮肤下按摩，打通痛点经络，减轻颈椎疼痛。</p>

    <div class="page_top">
      <div class="top_info clearfix" style="">
        <div class="fl_l title" style="font-size: 19px">颈椎按摩仪</div>
      </div>
      <div class="top_info clearfix">
        <div class="fl_l tit">当前模式：<span style="color: #1296db">{{ pattern }}</span></div>
        <div class="fl_l tit" >热敷：<span style="color: #1296db">{{ hot_fu }}</span></div>
      </div>

      <div class="top_info clearfix">
        <div class="fl_l tit">当前强度：<span style="color: #1296db">{{strength}}</span></div>
        <div class="fl_l tit">语音状态：<span style="color: #1296db">{{ying}}</span></div>
      </div>
      <div class=" top_info clearfix">
        <div class="fl_l" style="font-size: 14px;">当前电量：</div>
        <progress class="weui-progress__bar"  :percent="dianliang" stroke-width="15" style=" width: 52%;height: 15px;margin-top: 6px;"/>
      </div>
    </div>


    <div class="page_top page_top_two clearfix">
      <div class="big_box fl_l" @click="icon_btn(241,1)">
        <i class="iconfont" :class="pattern=='揉捏'?'hover':''">&#xe602;</i>
        <div :class="pattern=='揉捏'?'hover':''">揉捏</div>
      </div>
      <div class="big_box fl_l" @click="icon_btn(241,2)">
        <i class="iconfont" :class="pattern=='拍打'?'hover':''">&#xe8b9;</i>
        <div :class="pattern=='拍打'?'hover':''">拍打</div>
      </div>
      <div class="big_box fl_l" @click="icon_btn(241,3)">
        <i class="iconfont" :class="pattern=='锤击'?'hover':''">&#xe8b6;</i>
        <div :class="pattern=='锤击'?'hover':''">锤击</div>
      </div>
      <div class="big_box fl_l" @click="icon_btn(245,5)">
        <i class="iconfont" :class="addOrjian=='增强'?'hover':''">&#xe600;</i>
        <div :class="addOrjian=='增强'?'hover':''">增强</div>
      </div>

    </div>
    <div class="page_top page_top_two clearfix" style="margin-top: 0;">
      <div class="big_box fl_l" @click="icon_btn(248,2)">
        <i class="iconfont" :class="singer=='上一首'?'hover':''">&#xe649;</i>
        <div :class="singer=='上一首'?'hover':''">上一首</div>
      </div>
      <div class="big_box fl_l" @click="icon_btn(248,1)">
        <i class="iconfont" :class="singer=='播放/暂停'?'hover':''">&#xe7f1;</i>
        <div :class="singer=='播放/暂停'?'hover':''">播放/暂停</div>
      </div>
      <div class="big_box fl_l" @click="icon_btn(248,3)">
        <i class="iconfont" :class="singer=='下一首'?'hover':''">&#xe648;</i>
        <div :class="singer=='下一首'?'hover':''">下一首</div>
      </div>
      <div class="big_box fl_l" @click="icon_btn(246,6)">
        <!--<div class="down_icon box_icon"></div>-->
        <i class="iconfont" :class="addOrjian=='减弱'?'hover':''">&#xe664;</i>
        <div :class="addOrjian=='减弱'?'hover':''">减弱</div>
      </div>
    </div>
    <div class="page_top page_top_two clearfix" style="margin-top: 0;">
      <div class="big_box fl_l" @click="icon_btn(247,7)">
        <!--<div class=" hot_icon box_icon"></div>-->
        <i class="iconfont" :class="hot_fu=='打开'?'hover':''">&#xe647;</i>
        <div :class="hot_fu=='打开'?'hover':''">热敷</div>
      </div>
      <div class="big_box fl_l" @click="icon_btn(249,0)">
        <!--<div class=" hot_icon box_icon"></div>-->
        <i class="iconfont" :class="ying=='关闭'?'hover':''">&#xe6f8;</i>
        <div :class="ying=='关闭'?'hover':''">关闭语音</div>
      </div>
      <div class="big_box fl_l" @click="icon_btn(249,1)">
        <!--<div class=" hot_icon box_icon"></div>-->
        <i class="iconfont" :class="ying=='打开'?'hover':''">&#xe6f7;</i>
        <div :class="ying=='打开'?'hover':''">打开语音</div>
      </div>
      <div class="big_box fl_l" @click="icon_btn_alert(255,55)">
        <i class="iconfont" :class="num==255?'hover':''">&#xe672;</i>
        <div :class="num==255?'hover':''">关机</div>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  data () {
    return {
      num:0,
      shows:'',
      strength:'',
      pattern:'',
      hot_fu:"",
      dianliang:100,
      deviceId:0,
      serviceId:0,
      characteristicId:0,
      connectedDeviceId:0,
      serviceId_two:0,
      notifyCharacteristicsId:0,
      singer:"",
      ying:"",
      addOrjian:"",
    }
  },
  onLoad: function(options) {
    console.log(options);
    this.deviceId = options.deviceId
  },
  mounted() {
    //5.连接蓝牙> 匹配到的蓝牙设备ID 发送连接蓝牙的请求， 连接成功之后 应该断开蓝牙搜索的api，然后去获取所连接蓝牙设备的service服务
    var that = this;
    wx.createBLEConnection({
      deviceId:that.deviceId,
      success: function(res) {
        console.log("5.连接蓝牙",res);
        that.connectedDeviceId = that.deviceId;
        /* 6.获取连接设备的service服务 */
        that.getBLEDeviceServices(that.connectedDeviceId);
        wx.stopBluetoothDevicesDiscovery({
          success: function(res) {
            wx.showToast({
              title: "蓝牙已连接",
              icon: "success",
              duration: 2000
            });
            console.log('停止搜索',res)
          },
          fail(res) {
            // console.log("Error",res)
          }
        })
      },
      fail: function(res) {
        console.log(res)
      }
    })
  },
  methods: {
    mytouchstart: function(e){ console.log(e.timeStamp +'- touch start')
    },
    mytouchend: function(e){ console.log(e.timeStamp +'- touch end')
    },
    mytap: function(e){ console.log(e.timeStamp +'- tap')},


      slider3change(value) {
      console.log(value.target.value, "value")
    },
    /*转换成需要的格式*/
    buf2string(buffer) {
      var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x);
      return arr.map((char, i) => {
        return String.fromCharCode(char);
      }).join('');
    },

    receiveData(buf) {
      return this.hexCharCodeToStr(this.ab2hex(buf))
    },

    /*转成二进制*/
    ab2hex(buffer) {
      var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer), function(bit) {
          return ('00' + bit.toString(16)).slice(-2)
        }
      );
      return hexArr.join('')
    },

    /*转成可展会的文字*/
    hexCharCodeToStr(hexCharCodeStr) {
      var trimedStr = hexCharCodeStr.trim();
      var rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;
      var len = rawStr.length;
      var curCharCode;
      var resultStr = [];
      for (var i = 0; i < len; i = i + 2) {
        curCharCode = parseInt(rawStr.substr(i, 2), 16);
        resultStr.push(String.fromCharCode(curCharCode));
      }
      return resultStr.join('');
    },

    icon_btn_alert(i,j){
      var that = this;
      wx.showModal({
        title: '提示',
        content: '是否关机',
        success (res) {
          if (res.confirm) {
            that.icon_btn(i,j)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })

    },
    // 向蓝牙设备发送数据
    icon_btn(i,j) {
      if (i == 241 && j == 1) {
        console.log("揉捏", i,j)
      } else if (i == 241 && j == 2) {
        console.log("拍打", i,j)
      } else if (i == 241 && j == 3) {
        console.log("锤击", i,j)
      } else if (i == 245 && j == 5) {
        this.addOrjian = "增强";
        setTimeout(()=>{
          this.addOrjian = "";
        },200);
        console.log("增强", i,j)
      } else if (i == 246 && j == 6) {
        this.addOrjian = "减弱";

        setTimeout(()=>{
          this.addOrjian = "";
        },200);
        console.log("减弱", i,j)
      } else if (i == 247 && j == 7) {

        console.log("热敷", i,j)
      } else if (i == 248 && j == 2) {
        this.singer = "上一首";
        setTimeout(()=>{
          this.singer = "";
        },200);
        console.log("上一首", i,j)
      } else if (i == 248 && j == 1) {
        this.singer = "播放/暂停";
        setTimeout(()=>{
          this.singer = "";
        },200);
        console.log("播放/暂停", i,j)
      } else if (i == 248 && j == 3) {
        this.singer = "下一首";
        setTimeout(()=>{
          this.singer = "";
        },200);
        console.log("下一首", i,j)
      } else if (i == 249 && j == 0) {
        console.log("关闭提示音", i,j)
      } else if (i == 249 && j == 1) {
        console.log("打开提示音", i,j)
      } else {
        console.log("关机", i,j)
      }
      console.log(i,j,this.singer)

      var that = this;
      that.num = i
      console.log("characteristicId",that.notifyCharacteristicsId_,"that.serviceId_two",that.serviceId_two);

      let dataBuffer = new ArrayBuffer(5);
      let dataView = new DataView(dataBuffer);
      dataView.setUint8(0, 74);
      dataView.setUint8(1, 83);
      dataView.setUint8(2, 67);
      dataView.setUint8(3, i);
      dataView.setUint8(4, j);

      let dataHex = that.ab2hex(dataBuffer);
      that.writeDatas = that.hexCharCodeToStr(dataHex);
      wx.writeBLECharacteristicValue({
        deviceId: that.deviceId,
        serviceId: that.serviceId_two,
        characteristicId: that.notifyCharacteristicsId_,
        value: dataBuffer,
        success: function(res) {
          console.log(res, "res")

          console.log("sendData", res);
          console.log('发送的数据：' + that.writeDatas)
          if(that.num == 255){
            wx.navigateTo({
              url: `/pages/index/main`
            });
          }
        },
        fail: function(res) {
          console.log('向蓝牙设备发送数据fail', res)
        },
        complete: function(res) {
          console.log("complete", res)
        }
      })
      // }

      // }

    },


    //6. 获取蓝牙设备的service服务,获取的serviceId有多个要试着连接最终确定哪个是稳定版本的service 获取服务完后获取设备特征值
    getBLEDeviceServices(deviceId) {
      var that = this;
      setTimeout(() => {
        wx.getBLEDeviceServices({
          deviceId,
          success: function(res) {
            that.setlist = res;
            console.log("6. 获取蓝牙设备的service服务", res);
            // that.services = res.services;

            // console.log("that.services",that.services)

            for (let i = 0; i < res.services.length; i++) {
              if (res.services[i].isPrimary) {
                // console.log(res.services[i].uuid,"第"+i+"个UUID");
                //运行了两次
                that.getBLEDeviceCharacteristics(deviceId, res.services[0].uuid)
              }
            }
          },
          fail: (res) => {
            console.log(res)
          }
        })
      }, 2000)
    },
    // 7.获取蓝牙设备特征值    获取到的特征值有多个，最后要用的事能读，能写，能监听的那个值的uuid作为特征值id，
    getBLEDeviceCharacteristics(deviceId, uuid) {
      var that = this;
      that.serviceId_two = uuid;
      // console.log("uuid",uuid,"deviceId",deviceId,"that.serviceId_two ",that.serviceId_two )

      setTimeout(() => {
        wx.getBLEDeviceCharacteristics({
          deviceId,
          serviceId: uuid,
          success: function(res) {
            console.log("7.获取蓝牙设备特征值", res);
            that.notifyCharacteristicsId = res.characteristics;
            that.notifyCharacteristicsId_ = res.characteristics[0].uuid;
            for (var i = 0; i < res.characteristics.length; i++) {
              let item = res.characteristics[i];
              if (item.properties.read) {
                wx.readBLECharacteristicValue({
                  deviceId,
                  serviceId,
                  characteristicId: item.uuid,
                })
              }
              if (item.properties.write) {
                // console.log("item.uuid",item.uuid)
                // that.notifyBLECharacteristicValueChange(item.uuid)
              }
              if (item.properties.notify || item.properties.indicate) {
                wx.notifyBLECharacteristicValueChange({
                  deviceId: that.connectedDeviceId,
                  serviceId: that.serviceId_two,
                  characteristicId: item.uuid,
                  state: true,
                  complete(res) {
                    console.log("7.启动notify", res, "that.serviceId_two", that.serviceId_two);
                    /*用来监听手机蓝牙设备的数据变化*/
                    wx.onBLECharacteristicValueChange(function(res) {
                      // console.log("7.监听手机蓝牙设备的数据变化", res.value);
                      that.balanceData += that.buf2string(res.value);
                      that.hexstr += that.receiveData(res.value)
                      var pattern = new Uint8Array(res.value, 4, 1);
                      that.pattern = pattern[0];
                      // console.log("模式", pattern[0])

                      if (pattern == 1) {
                        that.pattern = "揉捏"
                      } else if (pattern == 2) {
                        that.pattern = "拍打"
                      } else {
                        that.pattern = "锤击"
                      }
                      var strength = new Uint8Array(res.value, 5, 1);
                      that.strength = strength[0];
                      // console.log("强度", strength[0])

                      var fuzai = new Uint8Array(res.value, 6, 1);
                      that.fuzai = fuzai[0];
                      // console.log("负载", fuzai[0])

                      var hot_fu = new Uint8Array(res.value, 7, 1);
                      that.hot_fu = hot_fu[0];
                      // console.log("热敷", that.hot_fu)
                      if (hot_fu[0] == 0) {
                        that.hot_fu = "关闭"
                      } else {
                        that.hot_fu = "打开"
                      }
                      var dianliang = new Uint8Array(res.value, 8, 1);
                      that.dianliang = dianliang[0] * 10;
                      // console.log("电量", that.dianliang)

                      var ying = new Uint8Array(res.value, 9, 1);
                      that.ying = ying[0];
                      if (ying[0] == 0) {
                        that.ying = "关闭"
                      } else {
                        that.ying = "打开"
                      }
                      // console.log("提示音", that.ying)
                    })
                  },
                  fail(res) {
                    console.log('7.启用低功耗蓝牙设备监听失败', res)
                  }
                })
              }
            }
          },
          fail: function(res) {
            console.log("7.错误", res)
          }
        })
      }, 1000)
    },

    /*转换成需要的格式*/
    buf2string(buffer) {
      var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x);
      return arr.map((char, i) => {
        return String.fromCharCode(char);
      }).join('');
    },

    receiveData(buf) {
      return this.hexCharCodeToStr(this.ab2hex(buf))
    },

    /*转成二进制*/
    ab2hex(buffer) {
      var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer), function(bit) {
          return ('00' + bit.toString(16)).slice(-2)
        }
      );
      return hexArr.join('')
    },

    /*转成可展会的文字*/
    hexCharCodeToStr(hexCharCodeStr) {
      var trimedStr = hexCharCodeStr.trim();
      var rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;
      var len = rawStr.length;
      var curCharCode;
      var resultStr = [];
      for (var i = 0; i < len; i = i + 2) {
        curCharCode = parseInt(rawStr.substr(i, 2), 16);
        resultStr.push(String.fromCharCode(curCharCode));
      }
      return resultStr.join('');
    },
    // 向蓝牙设备发送数据
    sendData(characteristicId, type, a) {
      console.log("characteristicId", characteristicId, "type", type, "分钟数", a)
      var that = this;
      let serviceId = that.serviceId_two;
      if (type == 1) {
        let dataBuffer = new ArrayBuffer(4);
        let dataView = new DataView(dataBuffer);
        dataView.setUint8(0, 74);
        dataView.setUint8(1, 83);
        dataView.setUint8(2, 67);
        dataView.setUint8(3, 15);
        let dataHex = that.ab2hex(dataBuffer);
        that.writeDatas = that.hexCharCodeToStr(dataHex);
        wx.writeBLECharacteristicValue({
          deviceId: that.connectedDeviceId,
          serviceId: serviceId,
          characteristicId: characteristicId,
          value: dataBuffer,
          success: function(res) {
            console.log("sendData", res);
            console.log('发送的数据：' + that.writeDatas)
          },
          fail: function(res) {
            console.log('向蓝牙设备发送数据fail', res)
          },
          complete: function(res) {
            console.log("complete", res)
          }
        })
      } else {
        // .prototype.map.call(new Uint8Array(dataBuffer), x => ('00' + x.toString(16)).slice(-2)).join('');
        // let dataBuffer = new ArrayBuffer(str.length)

        let dataBuffer = new ArrayBuffer(5);
        let dataView = new DataView(dataBuffer);
        dataView.setUint8(0, 74);
        dataView.setUint8(1, 83);
        dataView.setUint8(2, 67);
        dataView.setUint8(3, 240);
        dataView.setUint8(4, a);
        let dataHex = that.ab2hex(dataBuffer);
        that.writeDatas = that.hexCharCodeToStr(dataHex);
        console
        wx.writeBLECharacteristicValue({
          deviceId: that.connectedDeviceId,
          serviceId: serviceId,
          characteristicId: characteristicId,
          value: dataBuffer,
          success: function(res) {
            that.endetimeFlag = true;
            // that.$request({
            //   url: "/app/getUserOrderInProgress",
            //   method: "GET",
            //   data: {
            //     userId: that.userid,
            //     deviceCode:that.deviceName
            //   },
            //   success: function (res) {
            //     wx.hideLoading();

            console.log("res", res);
            that.createTime = new Date();
            that.endeTime = new Date(res.data.data.endeTime);

            //
            var now = that.createTime.getTime();
            // //设置截止时间
            var end = that.endeTime.getTime();
            // //时间差
            sytime = 0;
            sytime = end - now;
            // that.countdown()
            // }
            // });
            console.log("sendData", res);
            console.log('发送的数据：' + that.writeDatas)
          },
          fail: function(res) {
            console.log('向蓝牙设备发送数据fail', res)
          },
          complete: function(res) {
            console.log("complete", res)
          }
        })
      }

    },

    // 当不需要连接蓝牙了后就要关闭蓝牙，并关闭蓝牙模块
    // 断开设备连接
    closeConnect() {
      var that = this;
      if (that.connectedDeviceId) {
        wx.closeBLEConnection({
          deviceId: that.connectedDeviceId,
          success: function(res) {
            console.log("success-res", res)
            that.closeBluetoothAdapter()
          },
          fail(err) {
            console.log("fail-err", err)
          }
        })
      } else {
        that.closeBluetoothAdapter()
      }
    },

    // 关闭蓝牙模块
    closeBluetoothAdapter() {
      var that = this;
      wx.closeBluetoothAdapter({
        success: function(res) {
          console.log("关闭蓝牙模块res", res);
        },
        fail: function(err) {
          console.log("关闭蓝牙模块err", err);
        }
      })
    },
  },
  onHide(){
    // console.log(111111111111);
      // this.closeConnect();
  },

  created () {

  }
}
</script>

<style scoped>
  button{width: 25%;
    text-align: center;
    line-height: normal;background: transparent;display: inherit;
    display: block;
    border: 0;border-radius: 0;
    color: #fff;
    font-size: 15px;}
  .title_info{text-align: center;padding: 2% 10% 0%;font-size: 15px; color: #333;}
  /*css图片垂直居中样式（之前带span标签，现在不要用span这样写更好）*/
  .img_box{width: 90%; height: 110px; overflow: hidden; font-size:0; background: #f7f7f7; text-align: center;margin: 3% 5% 0;
    position: relative;}
  .img_box::after{content:''; display:inline-block;vertical-align:middle;}
  .img_box>img{ display: block !important; vertical-align:middle;width: 100% !important; max-height: 100%; max-width: 100%; margin: 0 auto;}
  /* 点击切换*/
  .hover { color: #1296db; }
  .iconfont { font-size: 32px; }
  .weui-progress__bar { border-radius:5px; border: 3px solid #333; }
  /*清除浮动*/
  /* IE6、7 专有 */
  .clearfix { zoom: 1; }
  .clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
  }
  .fl_l{ float: left; }
  .fl_r{ float: right; }

  .top_info{ }
  .page_all{ width: 100%;height: 100%;background-size: 100% 100%;position: fixed;background-image: url()}
  .page_top{ margin: 3% 5% 0 5%; border:  2px solid #333; padding: 5%; border-radius: 20px; color: #333;}
  .page_top_two{ width:84%;padding: 3% 3% 0;border: 0;font-size: 15px; }
  .page_top .tit{ width: 50%;margin-bottom: 10px; font-size: 17px; }
  .page_top .title{ text-align: center; width: 100%;margin-bottom: 10px; font-size: 20px; }
  .big_box{ width: 25%; text-align: center; }

</style>
